import { whiteList } from './basics.router'
import { Router, isNavigationFailure } from 'vue-router'
// import { useTitle } from '@vueuse/core'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user'
import { DEFAULT_ROUTE, LOGIN_ROUTE } from '@/constants/base.contant'

// 权限验证
export const createRouterGuards = (router: Router) => {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    NProgress.start()
    if (userStore.token) {
      if (to.path === LOGIN_ROUTE) {
        next({ path: DEFAULT_ROUTE })
        NProgress.done()
      } else {
        if (!userStore.menus.length) {
          await userStore.afterLogin()
          next({ ...to, replace: true })
        } else {
          next()
        }
      }
    } else {
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next({ path: LOGIN_ROUTE, query: { redirect: to.fullPath }, replace: true })
        NProgress.done()
      }
    }
  })
  router.afterEach((to, _, failure) => {
    // const title = useTitle()
    if (isNavigationFailure(failure)) {
      // console.log('failed navigation', failure)
    }
    if (to.meta.title) {
      // title.value = to.meta.title as string
    }
    NProgress.done()
  })
  router.onError(error => {
    console.log(error, '路由错误')
  })
}
